package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.zkoss.util.media.Media;

public class FileUtils {
	private static String folderPath = "E:/Studying/Java/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/EOnline"; 
	
	public static String saveFileFromMedia(Media media, String newName, String subFolder) throws IOException {
		
		// Thong tin ve file va folder luu
		String fileName;
		if (newName == null) {
			fileName = media.getName();
		} else {
			String fileExt = media.getFormat();
			fileName = newName + "." + fileExt;
		}

		// Truy cap folder luu
		File dFile;
		if(subFolder == null) {
			dFile = new File(folderPath);
		} else {
			dFile = new File(folderPath+"/"+subFolder);
		}
		dFile.mkdirs();
		
		//Tao file luu
		File file = new File(dFile, fileName);
		if (!file.exists())
			file.createNewFile();
		
		// Doc va luu file
		BufferedInputStream bis = new BufferedInputStream(media.getStreamData());
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

		int read = 0;
		byte[] bytes = new byte[1024];

		while ((read = bis.read(bytes)) != -1) {
			bos.write(bytes, 0, read);
		}

		bis.close();
		bos.flush();
		bos.close();
		
		return file.getName();
	}
}
